package com.aispeech.testcustom.services;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.aispeech.aios.sdk.manager.AIOSCustomizeManager;
import com.aispeech.testcustom.i.CustomResultCallBack;
import com.aispeech.testcustom.i.IServiceForBridgeService;
import com.aispeech.testcustom.listener.CustomizeListener;
import com.aispeech.testcustom.utils.TiLog;

import java.util.List;

public class AiosBridgeService extends Service {
    private CustomResultCallBack customResultCallBack;

    public AiosBridgeService() {
    }

    @Override
    public IBinder onBind(Intent intent) {

        TiLog.i("onBind do xxxxx");

        return new MyBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        TiLog.i("unbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        TiLog.i("AiosBridgeService onCreate");

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        TiLog.i("AiosBridgeService onStartCommand");

        return super.onStartCommand(intent, flags, startId);
    }

    private void registerCustomCmd(List list) {
        TiLog.d("注册语音自定义指令");
        AIOSCustomizeManager.getInstance().regCommands(list);
    }

    private void cleanRegisterCustomCmd(boolean unRegisterListener) {
        TiLog.d("清除语音自定义指令");
        AIOSCustomizeManager.getInstance().cleanCommands();
        if (unRegisterListener){
            AIOSCustomizeManager.getInstance().unregisterCustomizeListener();
        }
    }

    private void deleteCmdCallback() {
        if (null != this.customResultCallBack) {
            TiLog.d("清除语音自定义回调");
            this.customResultCallBack = null;
        }
    }

    private void bindCmdCallback() {
        if (null != customResultCallBack) {
            AIOSCustomizeManager.getInstance().registerCustomizeListener(new CustomizeListener
                    (customResultCallBack));
        } else {
            TiLog.e("the customResultCallBack is null , maybe haven't binded or inject failed!!");
        }
    }

    class MyBinder extends Binder implements IServiceForBridgeService {

        @Override
        public void registerCmd(List list) {
            AiosBridgeService.this.registerCustomCmd(list);
        }

        @Override
        public void injectCmdCallback(CustomResultCallBack callBack) {
            //将自定义指令回调接口注入
            TiLog.d("将自定义指令回调接口注入");
            AiosBridgeService.this.customResultCallBack = callBack;
            bindCmdCallback();
        }

        @Override
        public void deleteCmdCallback() {
            AiosBridgeService.this.deleteCmdCallback();
        }

        @Override
        public void cleanRegisterCmd(boolean unReg) {
            AiosBridgeService.this.cleanRegisterCustomCmd(unReg);
        }
    }
}
